package com.guotd.ticketSystem.controller;

import com.guotd.ticketSystem.entity.Airport;
import com.guotd.ticketSystem.mapper.AirportMapper;
import com.guotd.ticketSystem.utils.SessionUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/addAirport")
public class AddAirportServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String name = request.getParameter("name");
        String address = request.getParameter("address");
        String tel = request.getParameter("tel");
        String city = request.getParameter("city");
        Airport a = new Airport(name, address, city, tel);
        try {
            SqlSession session = SessionUtil.getSqlSession();
            AirportMapper airportMapper = session.getMapper(AirportMapper.class);
            int row = airportMapper.addAirport(a);
            session.commit();
            session.close();
            if (row > 0) {
                request.getSession().setAttribute("airport_msg", "添加成功！");
                response.sendRedirect("getAirports");
            }
        } catch (Exception e) {
            request.setAttribute("airport_msg", "添加失败，该机场已存在！");
            request.getRequestDispatcher("airport_add.jsp").forward(request, response);
        }
    }
}
